<template>
  <div class="batch-sign-container">
    <div class="sraech-con">
      <a-space>
        <a-input-group>
          <a-select v-model="searchType" :style="{ width: '120px' }" placeholder="first">
            <a-option value="customCodeList">定制编号</a-option>
            <a-option value="productSkuList">产品SKU</a-option>
          </a-select>
          <a-input v-model="searchValue" @press-enter="search" :style="{ width: '260px' }" placeholder="请输入精确的编号或者SKU" />
        </a-input-group>
        <a-button type="primary" @click="search">确认</a-button>
      </a-space>
      <!-- <div class="common-text mt5">*此处可以在输入状态使用扫码枪，输入编号或SKU获取去单据信息，只能拉取到待验收状态的单据。</div> -->
    </div>
    <div class="center">
      <a-scrollbar style="height: 100%; overflow: auto">
        <div style="padding: 10px; overflow: hidden">
          <div class="table-item mb10" v-for="(item, index) in tableList" :key="index">
            <div class="top clearfix">
              <div class="fl">
                <span>{{ item.companyName }}</span>
                <span>{{ item.children.length }}</span>
              </div>
              <div class="fr">
                <a-button type="text">移除</a-button>
              </div>
            </div>
            <div class="bottom">
              <a-table :data="item.children" size="mini" :pagination="false" :scroll="{ x: '100%' }" class="table-two-line">
                <template #columns>
                  <a-table-column title="图片" #cell="{ record }" :width="50">
                    <a-image @click="showBigImg(record)" :preview="false" :src="$extract(getPicList(record)[0], 'url')" width="40" height="40" />
                  </a-table-column>
                  <a-table-column title="产品SKU" #cell="{ record }" :width="120">
                    {{ $extract(record, 'product.productSku') }}
                  </a-table-column>
                  <a-table-column title="定制编号" #cell="{ record }" :width="80">
                    {{ record.customCode }}
                  </a-table-column>
                  <a-table-column title="销售员" #cell="{ record }" :width="60">
                    {{ $extract(record, 'saler.name') }}
                  </a-table-column>
                  <a-table-column title="材质" #cell="{ record }" :width="60">
                    {{ $extract(record, 'customInfo.material') }}
                  </a-table-column>
                  <a-table-column :width="120" title="材质单价(元/g)">
                    <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtAvgMaterial') }}</template>
                  </a-table-column>
                  <a-table-column title="数量" #cell="{ record }" :width="80">
                    {{ record.qtyPurchase }}
                  </a-table-column>
                  <a-table-column :width="120" title="单件加工费">
                    <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtAvgProcess') }}</template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="材质净重是指产品出库时扣除石头和链条之外的重量。">
                        <p>
                          <span>材质净重(g)</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.wgtNetMaterial') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="生产加工过程中主材质的损耗率">
                        <p>
                          <span>损耗率(%)</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.attritionRate') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="连耗重量，是指净重加上损耗的重量">
                        <p>
                          <span>连耗重量(g)</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.attritionRate') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="材质金额=材质单价*连耗重量">
                        <p>
                          <span>材质金额</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.amtMaterial') ? $extract(record, 'supplierCloseCost.amtMaterial') : '--' }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="100">
                    <template #title>
                      <a-popover content="加工费=单件加工费*数量">
                        <p>
                          <span class="required">加工费</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">{{ record.supplierCloseCost.amtAvgProcess * record.qtyPurchase ? record.supplierCloseCost.amtAvgProcess * record.qtyPurchase : '--' }}</template>
                  </a-table-column>

                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="如果石头是由供应商提供的，则供应商在交货的时可以填上石头费用">
                        <p>
                          <span>石头费用</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.amtStone') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="如果链条是由供应商提供的，则供应商在交货的时候可以填上链条费用。">
                        <p>
                          <span>链条费用</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.amtChain') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="120">
                    <template #title>
                      <a-popover content="本次定制单产生的其他费用">
                        <p>
                          <span>其他费用</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">
                      {{ $extract(record, 'supplierCloseCost.amtOther') }}
                    </template>
                  </a-table-column>
                  <a-table-column :width="100">
                    <template #title>
                      <a-popover content="合计金额=材质金额+加工费+石头费用+链条费用+其他费用">
                        <p>
                          <span class="required">合计金额</span>
                          <icon-question-circle />
                        </p>
                      </a-popover>
                    </template>
                    <template #cell="{ record, rowIndex }">{{ $extract(record, 'supplierCloseCost.amtTotal') ? $extract(record, 'supplierCloseCost.amtTotal') : '--' }}</template>
                  </a-table-column>
                  <a-table-column :width="120" title="税率">
                    <template #cell="{ record, rowIndex }">
                      <div>
                        <span> {{ $extract(record, 'supplierCloseCost.taxRate') }}%</span>
                        <span class="highlight">{{ record.supplierCloseCost.includeTax ? '（含税）' : '（不含税）' }}</span>
                      </div>
                    </template>
                  </a-table-column>
                  <a-table-column :width="120" title="税金">
                    <template #cell="{ record, rowIndex }">
                      <div>
                        <span> {{ $extract(record, 'supplierCloseCost.amtTax') ? $extract(record, 'supplierCloseCost.amtTax') : '--' }}</span>
                      </div>
                    </template>
                  </a-table-column>
                </template>
              </a-table>
            </div>
          </div>
        </div>
      </a-scrollbar>
    </div>
    <div class="footer flex-c-end">
      <a-space>
        <a-button class="gray-outline" @click="back">取消</a-button>
        <a-popover v-model:popup-visible="showPopoverVisible" trigger="click">
          <a-button class="gray-outline" @click="showPopoverVisible = true">驳回</a-button>
          <template #content>
            <a-textarea v-model="rejectText" placeholder="请输入拒绝原因" allow-clear />
            <div class="flex-c-end">
              <a-space>
                <a-button size="small" class="gray-outline" @click="showPopoverVisible = false">取消</a-button>
                <a-button size="small" type="primary" @click="submit(false)">确认</a-button>
              </a-space>
            </div>
          </template>
        </a-popover>
        <a-button type="primary" @click="submit(true)">确认签收</a-button>
      </a-space>
    </div>
  </div>
  <a-image-preview-group v-model:visible="visible" infinite :srcList="srcList" />
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { Message } from '@arco-design/web-vue'
  import { pageCustomOrderPurchase, batchPurchaseVerify } from '@/api/purchase'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  const visitedRouteStore = useVisitedRouteStore()
  const router = useRouter()
  const route = useRoute()
  let searchType = ref('customCodeList')
  let searchValue = ref('')
  let tableList = ref<Array<any>>([])
  let srcList = ref<Array<any>>([])
  let visible = ref(false)
  let showPopoverVisible = ref(false)
  let rejectText = ref('')
  const init = () => {
    let str: any = route.query.list
    let arr = JSON.parse(str)
    setLsit(arr)

    console.log(tableList.value)
  }

  const setLsit = (list: any) => {
    list.forEach((e: any) => {
      let index = tableList.value.findIndex((el: any) => el.companyId == e.supplierCloseCost?.supplierCompany?.companyId)
      if (index != -1) {
        let childrenIndex = tableList.value[index].children.findIndex((ell: any) => ell.id == e.id)
        if (childrenIndex == -1) tableList.value[index].children.push(e)
      } else {
        let obj = {
          companyName: e.supplierCloseCost.supplierCompany.companyName,
          companyId: e.supplierCloseCost.supplierCompany.companyId,
          children: [e],
        }
        tableList.value.push(obj)
      }
    })
  }

  const getPicList = (item: any) => {
    return item.customInfo?.customPicList || []
  }

  const showBigImg = (item: any) => {
    let arr = getPicList(item)
    srcList.value = arr.map((e: any) => e.url)
    visible.value = true
  }

  const search = async () => {
    if (!searchValue.value) return Message.warning('请输入搜索内容')
    let params = {}

    params[searchType.value] = searchValue.value.split(',')

    const res: any = await pageCustomOrderPurchase(params)
    if (res) {
      setLsit(res.data?.records || [])
    }
  }

  const submit = async (accept: boolean) => {
    if (!rejectText.value && !accept) return Message.error('请输入驳回原因')

    let arr: any = []
    tableList.value.forEach((e) => {
      e.children.forEach((item: any) => {
        arr.push(item.id)
      })
    })

    let params = {
      accept: accept,
      idList: arr,
      rejectReason: rejectText.value,
    }
    const res: any = await batchPurchaseVerify(params)
    if (res) {
      Message.success(`${accept ? '签收' : '驳回'}成功`)
      setTimeout(() => {
        back()
      }, 1000)
    }
  }

  const back = () => {
    // 返回广告活动
    router.replace('/purchase/purchaseManagement/customPurchase')
    visitedRouteStore.removeVisitedRoute(route)
  }

  onMounted(init)
</script>

<style lang="less" scoped>
  :deep(.arco-scrollbar) {
    height: 100%;
  }

  .table-item {
    .top {
      height: 40px;
      line-height: 40px;
      padding: 0 20px;
      background-color: #f2f3f5;
    }
  }

  .batch-sign-container {
    flex: 1;
    width: 100%;
    height: calc(100vh - @headerHeight);
    // background-color: white;
    flex-wrap: wrap;
    .sraech-con {
      padding: 10px 20px;
      background: white;
      height: 70px;
      width: 100%;
    }

    .center {
      width: 100%;
      margin-top: 10px;
      padding: 10px;
      height: calc(100% - @headerHeight - 100px);
      background-color: white;
    }

    .footer {
      margin-top: 5px;
      padding-right: 20px;
      width: 100%;
      height: 40px;
    }
  }
</style>
